/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.web.editors.EditorCallback;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.io.File;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class FileListView extends AbstractView<String> {

    private Listbox listbox;

    private String scope;

    /**
     * @param cb
     */
    protected FileListView(EditorCallback<String> cb, String scope, Component component) {
        super(component, cb);
        this.scope = scope;
    }

    @Override
    protected void createContent(Component parent) {
        // 内容
        listbox = new Listbox();
        listbox.setId("fileListView_listbox_result");
        listbox.setVflex("1");
        listbox.setHflex("1");
        Listhead listhead = new Listhead();
        listhead.setSizable(true);
        listhead.setParent(listbox);
        Listheader listheader = new Listheader();
        listheader.setLabel(Labels.getLabel("editor.file.no"));
        listheader.setHflex("1");
        listheader.setParent(listhead);
        listheader = new Listheader();
        listheader.setLabel(Labels.getLabel("editor.file.name"));
        listheader.setHflex("1");
        listheader.setParent(listhead);
        listbox.setParent(parent);
        redraw();
    }

    private void redraw() {
        String[] fileName = new File(StudioApp.getServletContext().getRealPath("/apps/" + Contexts.getProject().getId() + "/" + scope)).list();
        if (fileName != null && fileName.length != 0) {
            for (int i = 0; i < fileName.length; i++) {
                String name = fileName[i];
                Listitem row = new Listitem();
                row.setValue("/apps/" + Contexts.getProject().getId() + "/" + scope + "/" + fileName[i]);
                row.appendChild(new Listcell(i + ""));
                row.appendChild(new Listcell(name));
                row.setParent(listbox);
                row.addEventListener(Events.ON_DOUBLE_CLICK, this);
            }
        }
    }

    public void onEvent(Event event) throws Exception {
        if (event.getTarget() instanceof Listitem) {
            Listitem row = (Listitem) event.getTarget();
            cb.setValue(row.getValue() + "");
            listbox.getRoot().detach();
            onCloseClick(win);
        }
    }
}
